package mall

import (
	"fmt"
	"time"

	"gorm.io/gorm"
	"main.go/global"
	"main.go/model/mall"
	mallReq "main.go/model/mall/request"
	"main.go/utils"
)

type OrderService struct{}

func (s *OrderService) Create(u *mall.MallOrder) (out *mall.MallOrder, err error) {
	var data mall.MallOrder
	err = global.EVA_DB.Create(&data).Error
	return u, err
}

func (s *OrderService) Delete(id int) (err error) {
	// 事务
	return global.EVA_DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("id = ?", id).Delete(&mall.MallOrder{}).Error; err != nil {
			return err
		}
		return nil
	})
}

func (s *OrderService) Update(req *mall.MallOrder) (out *mall.MallOrder, err error) {
	updateData := make(map[string]interface{})
	if req.PayConfigId != 0 {
		updateData["pay_config_id"] = req.PayConfigId
	}
	if req.Type != 0 {
		updateData["type"] = req.Type
	}
	if req.PayStatus != 0 {
		updateData["pay_status"] = req.PayStatus
	}
	if req.OrderStatus != 0 {
		updateData["order_status"] = req.OrderStatus
	}
	if req.Amount != 0 {
		updateData["amount"] = req.Amount
	}

	if req.UserID != 0 {
		updateData["user_id"] = req.UserID
	}
	if len(req.OutTradeNo) > 0 {
		updateData["out_trade_no"] = req.OutTradeNo
	}
	if len(req.TransactionId) > 0 {
		updateData["transaction_id"] = req.TransactionId
	}

	err = global.EVA_DB.Model(&mall.MallOrder{}).Where(mall.MallOrder{
		EVA_MODEL: global.EVA_MODEL{
			ID: req.ID,
		},
	}).Updates(updateData).Error
	return out, err
}

func (s *OrderService) List(req *mallReq.MallOrderListReq) (list []*mall.MallOrder, total int64, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.Page - 1)
	fmt.Println(limit, offset)
	db := global.EVA_DB.Model(&mall.MallOrder{})
	// 如果有条件搜索 下方会自动创建搜索语句
	if req.PayConfigId != 0 {
		db = db.Where("pay_config_id = ?", req.PayConfigId)
	}

	if req.PayStatus != 0 {
		db = db.Where("pay_status = ?", req.PayStatus)
	}
	if req.OrderStatus != 0 {
		db = db.Where("order_status = ?", req.OrderStatus)
	}

	if req.Amount != 0 {
		db = db.Where("amount = ?", req.Amount)
	}
	if req.UserID != 0 {
		db = db.Where("user_id = ?", req.UserID)
	}
	if len(req.TransactionId) > 0 {
		db = db.Where("transaction_id = ?", req.TransactionId)
	}

	if len(req.OutTradeNo) > 0 {
		db = db.Where("out_trade_no = ?", req.OutTradeNo)
	}
	if len(req.CourierNo) > 0 {
		db = db.Where("courier_no = ?", req.CourierNo)
	}
	if req.StartCreatedAt != 0 && req.EndCreatedAt != 0 {
		t1 := time.Unix(req.StartCreatedAt, 0).In(utils.ShLocation)
		t2 := time.Unix(req.EndCreatedAt, 0).In(utils.ShLocation)
		db = db.Where("created_at BETWEEN ? AND ?", t1, t2)
	}
	err = db.Count(&total).Error
	if err != nil {
		return list, total, err
	}

	err = db.Order("id desc").Limit(limit).Offset(offset).Find(&list).Error
	return list, total, err
}
